package com.nondo.rdp.finance.endpoint.api.admin;

import com.nondo.rdp.auth.common.UserUtils;
import com.nondo.rdp.auth.domain.User;
import com.nondo.rdp.core.common.CommUtil;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.domain.attach.Attach;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.finance.domain.collection.CollList;
import com.nondo.rdp.finance.domain.collection.XimalayaAlbum;
import com.nondo.rdp.finance.domain.collection.XimalayaAlbumList;
import com.nondo.rdp.finance.domain.course.Course;
import com.nondo.rdp.finance.domain.course.Section;
import com.nondo.rdp.finance.model.CollListBean;
import com.nondo.rdp.finance.service.collection.CollListService;
import com.nondo.rdp.finance.service.collection.XimalayaAlbumListService;
import com.nondo.rdp.finance.service.collection.XimalayaAlbumService;
import com.nondo.rdp.finance.service.course.CourseService;
import com.nondo.rdp.finance.service.course.SectionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

@RestController("apiAdminCollection")
@RequestMapping("/api/admin/collection")
public class CollectionEndpoint {
    @Autowired
    CollListService collListService;

    @Autowired
    XimalayaAlbumService ximalayaAlbumService;

    @Autowired
    XimalayaAlbumListService ximalayaAlbumListService;

    @Autowired
    CourseService courseService;

    @Autowired
    SectionService sectionService;

    @Autowired
    CommUtil commUtil;

    /**
     * 获取采集列表列表
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("/list")
    public View list(HttpServletRequest request, HttpServletResponse response) {
        View view = new View(20000, "获取列表成功");

        List collList = collListService.findAll();

        view.setData(collList);
        return view;
    }

    /**
     * 添加采集列表
     *
     * @param request
     * @param response
     * @param result
     * @return
     */
    @RequestMapping(value = "/add", produces = "application/json;charset=UTF-8")
    public View<CollList> add(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody CollList collList, BindingResult result) {
        View<CollList> view = new View<>(20000, "添加成功");

        User user = UserUtils.getUser(request, response);

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            //判断是否已经存在了
            CollList isExist = this.collListService.findByAlbumId(collList.getAlbumId());
            if (isExist != null) {
                return View.ofError("已经存在该项目，不能重复添加");
            }

            this.collListService.save(collList);
        }
        return view;
    }

    /**
     * 更新采集列表
     *
     * @param request
     * @param response
     * @param result
     * @return
     */
    @RequestMapping("/update")
    public View<CollList> update(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody CollList collList, BindingResult result) {
        View<CollList> view = new View<>(20000, "更新成功");

        User user = UserUtils.getUser(request, response);

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            this.collListService.update(collList);
        }

        return view;
    }

    /**
     * 更新采集列表
     *
     * @param request
     * @param response
     * @param result
     * @return
     */
    @RequestMapping("/storage")
    public View<CollList> storage(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody CollListBean collListBean, BindingResult result) {
        View<CollList> view = new View<>(20000, "采集入库成功");

        User user = UserUtils.getUser(request, response);

        if (result.hasErrors()) {
            view.setCode(40000);
            view.setMessage(ValidateUtil.first(result.getAllErrors()));
        } else {
            //处理传输的数据
            String[] albumIds = collListBean.getAlbumIds().split(",");

            //2、保存到课程信息表中
            for (String item : albumIds) {
                //获取课程信息
                XimalayaAlbum ximalayaAlbum = this.ximalayaAlbumService.findByAlbumId(Integer.parseInt(item));
                if (ximalayaAlbum == null) {
                    continue;
                }

                //检查数据库是否已经存在
                Course isCourseExist = this.courseService.findByAlbumId(Integer.parseInt(item));
                Course course = new Course();
                if (isCourseExist == null) {
                    //上传图片到服务器
                    Map descImgMap = commUtil.uploadImageFromUrl(ximalayaAlbum.getCoverOrigin());
                    Attach descImg = new Attach();
                    descImg.setPath(descImgMap.get("path").toString());
                    course.setDescImg(descImg);

                    Map mainImgMap = commUtil.uploadImageFromUrl(ximalayaAlbum.getCoverOrigin());
                    Attach mainImg = new Attach();
                    mainImg.setPath(mainImgMap.get("path").toString());
                    course.setMainImg(mainImg);

                    //保存课程
                    course.setAlbumId(ximalayaAlbum.getAlbumId());
                    course.setName(ximalayaAlbum.getTitle());
                    course.setDescription((ximalayaAlbum.getShortIntro() != null) ? ximalayaAlbum.getShortIntro() : ximalayaAlbum.getTitle());
                    course.setType(0);//默认为课程
                    course.setTeacher(ximalayaAlbum.getNickname());
                    course.setIntroduction(ximalayaAlbum.getCustomSubTitle());
                    course.setStatus(0);//默认下架
                    course.setMold(1);//这里只能是音频
                    course.setFree(1);//免费课程
                    course.setHome(0);
                    course.setRecommend(0);
                    this.courseService.save(course);
                } else {
                    course = isCourseExist;
                }

                //3、获取列表
                List<XimalayaAlbumList> ximalayaAlbumListList = this.ximalayaAlbumListService.findByAlbumId(ximalayaAlbum.getAlbumId());

                //4、保存到课节中
                for (XimalayaAlbumList row : ximalayaAlbumListList) {
                    //检查数据库中是否已经存在
                    Section isSectionExist = this.sectionService.findByAlbumIdAndTrackId(row.getAlbumId(), row.getTrackId());
                    if (isSectionExist == null) {
                        //保存课节
                        Section section = new Section();
                        section.setCourse(course);
                        section.setCourseId(course.getId());
                        section.setAlbumId(row.getAlbumId());
                        section.setTrackId(row.getTrackId());
                        section.setVideoUrl(row.getPlayUrl32());
                        section.setName(row.getTitle());
                        section.setPublisher(user);
                        section.setType(0);
                        section.setContent(row.getTitle());
                        this.sectionService.save(section);
                    }
                }
            }
        }

        return view;
    }
}